'use strict';

const createConfig = require('uni-config-center');
const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const uidObj = require('uni-id');
const {
	Controller
} = require('uni-cloud-router');

const dbcmd = uniCloud.database().command;

module.exports = class GoodsController extends Controller {

	// 详情v2（提升查询速度）
	async detailV2() {
		let response = {
			code: 1,
			goods: {},
			seckill: {},
			group: {}
		};
		
		const start = Date.now();
		const nowdate = start;
		
		const {
			goods_id,
			share_mid,
			seckill_id,
			group_id,
			admin
		} = this.ctx.data;
		
		// 产品状态
		let goods_state = '';
		const goodsRes = await this.db.collection('usemall-goods').doc(goods_id).field({
			cids: false,
			stock_wh_num: false,
			sold_out_time: false,
			collect: false,
			share_cnt: false,
			share: false,
			visit_cnt: false,
			visit: false,
			search_tags: false,
			create_time: false,
			create_uid: false,
			create_uname: false,
			last_modify_time: false,
			last_modify_uid: false,
			last_modify_uname: false
		}).get();
		const [goods] = goodsRes.data;
		
		if (!(goods && goods._id)) {
			response.msg = `当前商品不存在`;
			return response;
		}
		goods_state = goods.state;
		if (goods_state != '销售中' && !admin) {
			switch (goods_state) {
				case '待审核':
					response.msg = `当前商品未开售`;
					break;
				case '已下架':
					response.msg = `当前商品已下架`;
					break;
				default:
					response.msg = `当前商品${goods_state}`;
					break;
			}
			return response;
		}
		
		response.goods = goods;
		
		// 秒杀活动
		if (seckill_id) {
			response.seckill = await this.service.marketing.getSeckill(seckill_id);
			// 验证当前商品是否存在活动中
			if (response.seckill && !response.seckill.goods_ids.find(x => x == goods_id)) {
				response.msg = `秒杀活动中不存在当前商品`;
				return response;
			}
			
			// 当前商品
			response.seckill.goods_obj = response.seckill.goods_objs.find(x => x._id == goods_id);
			
			delete response.seckill.goods_ids;
			delete response.seckill.goods_objs;
		} 
		// 拼团活动
		if (group_id) {
			response.group = await this.service.marketing.getGroup(group_id);
			// 验证当前商品是否存在活动中
			if (response.group && response.group.goods_id !== goods_id) {
				response.msg = `拼团活动中不存在当前商品`;
				return response;
			}
		} 
		
		// 增加测试环境下 商品，请勿购买提示 
		if (uidConfig.config('env') === 'dev') {
			response.goods.name_pw = '【测试商品，请勿购买】' + (response.goods.name_pw || '');
		}
		
		// 访问数
		response.goods.visit_cnt += 1;
		const goodsUpdateObj = {
			visit_cnt: this.db.command.inc(1)
		}
		
		if (share_mid) {
			// 分享数
			response.goods.share_cnt += 1;
			goodsUpdateObj.share_cnt = this.db.command.inc(1);
		}
		
		// 更新商品访问数、分享数
		await this.db.collection('usemall-goods').doc(goods_id).update(goodsUpdateObj);
		
		// 开启 SKU
		response.goods.isku = !!(goods.skus && goods.skus.find(s => s.enable && s.arrs && s.arrs.length));
		if (response.goods.isku) {
			const skuRes = await this.db.collection('usemall-goods-sku').where({goods_id}).get();
			response.goods_skus = skuRes.data;
		}
		
		let end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	// 详情扩展（提升查询速度）
	async detailEx() {
		let response = {
			code: 1,
			// goods: {},
			goods_detail: {},
			// goods_skus: [],
			evaluate: [],
			evaluate_cnt: 0
		};
		
		let start = Date.now();
		const {
			goods_id,
			share_mid,
			seckill_id,
			group_id,
			admin
		} = this.ctx.data;
		
		// 产品状态
		let goods_state = '';
		let goods = await this.db.collection('usemall-goods').doc(goods_id).field({
			cids: false,
			stock_wh_num: false,
			sold_out_time: false,
			collect_cnt: false,
			collect: false,
			share_cnt: false,
			share: false,
			visit_cnt: false,
			visit: false,
			search_tags: false,
			create_time: false,
			create_uid: false,
			create_uname: false,
			last_modify_time: false,
			last_modify_uid: false,
			last_modify_uname: false
		}).get();
		
		if (!goods || goods.data.length <= 0) {
			response.msg = `当前产品不存在`;
			return response;
		}
		goods_state = goods.data[0].state;
		if (goods_state != '销售中' && !admin) {
			switch (goods_state) {
				case '待审核':
					response.msg = `当前产品未开售`;
					break;
				case '已下架':
					response.msg = `当前产品已下架`;
					break;
				default:
					response.msg = `当前产品${goods_state}`;
					break;
			}
			return response;
		}
		
		let collected = 0;
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				const collect = await this.db.collection('usemall-member-collect').where({
					create_uid: user.uid,
					goods: goods_id
				}).get();
				// 是否已收藏
				if (collect && collect.data.length > 0 && collect.data[0].state == '已收藏') {
					collected = 1;
				}
				
				// 记录请求参数
				const param = {
					id: goods_id,
					mid: share_mid,
					seckill_id,
					group_id,
					__type: group_id ? 'group' : seckill_id ? 'seckill' : ''
				};
		
				// 记录足迹（异步记录，提高响应时间）
				let obj_id = user.uid + goods_id;
				this.db.collection('usemall-goods-history').doc(obj_id).update({
					visit_cnt: this.db.command.inc(1),
					version: this.db.command.inc(1),
					param: param,
					state: goods_state,
					last_modify_uid: user.uid,
					last_modify_time: Date.now()
				}).then(res => {
					if (res && res.updated <= 0) {
						this.db.collection('usemall-goods-history').doc(obj_id).set({
							goods: goods_id,
							param: param,
							sort: 0,
							visit_cnt: 1,
							version: 1,
							state: goods_state,
							create_uid: user.uid,
							create_time: Date.now(),
							last_modify_time: Date.now()
						});
					}
				});
			}
		}
		
		// Object.assign(response.goods, { collected }, goods.data[0]);
		// // 增加测试环境下 商品，请勿购买提示
		// if (uidConfig.config('env') === 'dev') {
		// 	response.goods.name_pw = '【测试商品，请勿购买】' + (response.goods.name_pw || '');
		// }
		
		const detail = this.db.collection('usemall-goods-detail').where({goods_id}).get();
		// const sku = this.db.collection('usemall-goods-sku').where({goods_id}).get();
		const evaluate = this.db.collection('usemall-goods-comment').where({goods_id: goods_id,state: '显示'})
			.orderBy('create_time', 'desc')
			.limit(3)
			.get();
		const evaluateCount = this.db.collection('usemall-goods-comment').where({goods_id: goods_id,state: '显示'}).count();
		
		// 获取会员设置项
		const memberParameter = this.db.collection('usemall-member-parameter').limit(1).field({ desc: false, vip_desc: false }).get();
		// 获取积分设置项
		const integralParameter = this.db.collection('usemall-integral-parameter').limit(1).get();
		// 商品价格说明
		const appParameter = this.db.collection('usemall-app-parameter').limit(1).get();
		
		const datas = await Promise.all([detail, evaluate, evaluateCount, memberParameter, integralParameter, appParameter]);
		
		const detailRes = datas[0];
		// const skuRes = datas[1];
		const evaluateRes = datas[1];
		const evaluateCntRes = datas[2];
		const memberParameterRes = datas[3];
		const integralParameterRes = datas[4];
		const appParameterRes = datas[5];
		
		if (detailRes.data && detailRes.data.length === 1) {
			response.goods_detail = detailRes.data[0];
		}
		// if (skuRes && skuRes.data) {
		// 	response.goods_skus = skuRes.data;
		// }
		if (evaluateCntRes && evaluateCntRes.total) {
			response.evaluate_cnt = evaluateCntRes.total;
			response.evaluate = evaluateRes.data;
		}
		
		response.member_setting = memberParameterRes.data && memberParameterRes.data[0];
		response.integral_setting = integralParameterRes.data && integralParameterRes.data[0];
		response.goods_setting = appParameterRes.data && appParameterRes.data[0];
		
		response.collected = collected; 
		
		let end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 列表
	async list() {
		let response = {
			code: 1,
			goods: []
		};

		let start = Date.now();
		// 请求参数
		const req = this.ctx.data;
		let {
			cid,
			sid,
			keyword,
			limited,
			hot
		} = req;

		if (keyword) keyword = keyword.trim();

		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
			}
		}

		if (sid) {
			// 通过热门搜索
			const hot = await this.db.collection('usemall-search-hot').doc(sid).get();
			if (hot && hot.data.length > 0) {
				keyword = hot.data[0].keyword;
				// 修改搜索记录次数
				await this.db.collection('usemall-search-hot').doc(sid).update({
					last_modify_time: Date.now(),
					last_modify_uid: uid,

					version: this.db.command.inc(1),
					search_cnt: this.db.command.inc(1)
				});
			}
		}

		if (keyword && uid) {
			// 记录搜索历史			
			await this.db.collection('usemall-search-history').where({
				create_uid: uid,
				keyword: keyword
			}).update({
				search_cnt: this.db.command.inc(1),
				version: this.db.command.inc(1),
				last_modify_uid: uid,
				last_modify_time: Date.now()
			}).then(async res => {
				if (res && res.updated <= 0) {
					await this.db.collection('usemall-search-history').add({
						keyword,
						search_cnt: 1,
						version: 1,
						create_uid: uid,
						create_time: Date.now(),
						last_modify_uid: uid,
						last_modify_time: Date.now()
					});
				}
			});
		}
		
		const whereArrs = [];
		
		let whereObj = { state: '销售中' };
		if (limited == 1) whereObj.limited = 1;
		if (hot == 1) whereObj.hot = 1;
		if (cid) whereObj.cids = cid;
		
		whereArrs.push(whereObj);
		
		if (keyword) {
			let whereObj2 = this.db.command.or([{
				name: new RegExp(keyword),
			},{
				search_tags: keyword
			}]);
			
			whereArrs.push(whereObj2);
		} 
		
		const goods = await this.db.collection('usemall-goods')
			.where(this.db.command.and(whereArrs))
			.orderBy(req.sidx, req.sord)
			.skip((req.page - 1) * req.rows)
			.limit(req.rows)
			.get();

		response.goods = goods.data;

		let end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	// 加入购物车
	async addcart() {
		let start = Date.now();
		let nowdate = start;
		
		let response = {
			code: 1
		};
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		// 请求参数
		const req = this.ctx.data;
		let {
			goods_id,
			goods_num,
			goods_sku,
			goods_sku_id
		} = this.ctx.data;
		
		let obj_id = uid + goods_id + (goods_sku || '');
		let cart = await this.db.collection('usemall-goods-cart').doc(obj_id).update({
			goods_num: this.db.command.inc(goods_num),
			goods_sku: goods_sku,
			goods_sku_id: goods_sku_id,
			version: this.db.command.inc(1),
			last_modify_uid: uid,
			last_modify_time: nowdate
		});
		if (cart && cart.updated <= 0) {
			cart = await this.db.collection('usemall-goods-cart').doc(obj_id).set({
				goods: goods_id,
				goods_num,
				goods_sku,
				goods_sku_id,
				version: 1,
				create_uid: uid,
				create_time: nowdate,
				last_modify_time: nowdate
			});
		}

		console.log(`耗时：${Date.now() - start}ms`);
		response.cart = cart;
		response.code = 0;
		response.msg = `加入成功`;
		return response;

	}
	// 购买商品详情
	async detail2order() {
		let start = Date.now();
		let response = {
			code: 1
		};
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		// 请求参数
		const req = this.ctx.data;
		
		let {
			goods_id,
			cart_ids,
			goods_sku_id,
			seckill_id,
			group_id,
			group_chief_id
		} = this.ctx.data
		
		let goods = [];
		let goodsData = {};

		let goodsRes = {};
		let skuRes = {};
		
		// 运费模板
		const tpls = [];

		if (goods_id) {
			// 从商品详情页下单
			goodsRes = await this.db.collection('usemall-goods').doc(goods_id).field({
				cids: false,
				stock_wh_num: false,
				sold_out_time: false,
				skus: false,
				collect_cnt: false,
				collect: false,
				share_cnt: false,
				share: false,
				visit_cnt: false,
				visit: false,
				search_tags: false,
				create_time: false,
				create_uid: false,
				create_uname: false,
				last_modify_time: false,
				last_modify_uid: false,
				last_modify_uname: false
			}).get();
			console.log('goodsRes', goodsRes);
			if (!(goodsRes && goodsRes.data.length == 1)) {
				response.msg = '当前下单商品不存在';
				return response;
			}
			goodsData = goodsRes.data[0];
			let goodsState = goodsData.state;
			if (goodsState != '销售中') {
				switch (goodsState) {
					case '待审核':
						response.msg = `当前产品未开售`;
						break;
					case '已下架':
					default:
						response.msg = `当前产品${goodsState}`;
						break;
				}
				return response;
			}

			// 默认下单数量1
			goodsData.goods_num = 1;

			let goods_sku = {};
			if (goods_sku_id) {
				// 商品存在 sku
				skuRes = await this.db.collection('usemall-goods-sku').doc(goods_sku_id).get();
				if (skuRes && skuRes.data.length === 1) {
					goods_sku = skuRes.data[0];
				}
			}
			goods.push({
				goods: goodsData,
				goods_sku: goods_sku
			});
			
			if (goodsData.freight_tpl) tpls.push(goodsData.freight_tpl);
		} else if (cart_ids && cart_ids.length > 0) {
			// 从购物车下单
			let goodsCartRes = await this.db.collection('usemall-goods-cart').where({
				create_uid: uid,
				_id: this.db.command.in(cart_ids)
			}).get();
			if (!(goodsCartRes && goodsCartRes.data.length > 0)) {
				response.msg = '当前购物车不存在';
				return response;
			}
			let goodsCarts = goodsCartRes.data;
			let goodsIds = goodsCarts.map(x => x.goods);
			let goodsSkuIds = goodsCarts.filter(x => x.goods_sku).map(x => x.goods_sku);

			goodsRes = await this.db.collection('usemall-goods').where({
				_id: this.db.command.in(goodsIds)
			}).field({
				cids: false,
				stock_wh_num: false,
				sold_out_time: false,
				skus: false,
				collect_cnt: false,
				collect: false,
				share_cnt: false,
				share: false,
				visit_cnt: false,
				visit: false,
				search_tags: false,
				create_time: false,
				create_uid: false,
				create_uname: false,
				last_modify_time: false,
				last_modify_uid: false,
				last_modify_uname: false
			}).get();
			if (!(goodsRes && goodsRes.data.length > 0)) {
				response.msg = '当前购物车商品不存在';
				return response;
			}
			let goodsDatas = goodsRes.data;
			let goodsSkus = [];
			
			if (goodsSkuIds && goodsSkuIds.length) {
				skuRes = await this.db.collection('usemall-goods-sku').where({
					goods_id: this.db.command.in(goodsIds),
					goods_sku: this.db.command.in(goodsSkuIds)
				}).get();
				if (skuRes.data && skuRes.data.length) {
					goodsSkus = skuRes.data;
				}
				
				if (skuRes.data.length !== goodsSkuIds.length) {
					response.sku_msg = '当前购物车的商品存在已失效SKU';
				}
			}
			

			goodsCarts.forEach(x => {
				goodsData = goodsDatas.find(g => g._id == x.goods);
				// 购物车商品数量
				goodsData.goods_num = x.goods_num;
				goods.push({
					goods: goodsData,
					goods_sku: goodsSkus.find(g => g.goods_id == x.goods && g.goods_sku == x.goods_sku),
					cart: x
				});
				
				if (goodsData.freight_tpl) tpls.push(goodsData.freight_tpl);
			});
		}

		// 获取会员设置项
		const memberParameter = this.db.collection('usemall-member-parameter').limit(1).field({ desc: false, vip_desc: false }).get();
		// 获取积分设置项
		const integralParameter = this.db.collection('usemall-integral-parameter').limit(1).get();
		const execPromises = [memberParameter, integralParameter];
		
		if (tpls.length) {
			// 快递费模板
			const expressFee = this.db.collection('usemall-freight-template').where({
					_id: this.db.command.in(tpls),
					state: 1
				})
				.field({
					areas: true
				})
				.get();
			execPromises.push(expressFee);
		}
		
		const datas = await Promise.all(execPromises);
		
		const memberParameterRes = datas[0];
		const integralParameterRes = datas[1];
		const expressFeeRes = datas[2];
		
		response.member_setting = memberParameterRes.data && memberParameterRes.data[0];
		response.integral_setting = integralParameterRes.data && integralParameterRes.data[0];
		response.express_fees = expressFeeRes && expressFeeRes.data || [];
		
		// 开具发票
		response.invoice = uidConfig.config('invoice');
		
		// 秒杀活动
		if (seckill_id) {
			response.seckill = await this.service.marketing.getSeckill(seckill_id);
			// 验证当前商品是否存在活动中
			if (response.seckill && !response.seckill.goods_ids.find(x => x == goods_id)) {
				response.msg = `秒杀活动中不存在当前下单商品`;
				return response;
			}
			
			// 当前商品
			response.seckill.goods_obj = response.seckill.goods_objs.find(x => x._id == goods_id);
			
			delete response.seckill.goods_ids;
			delete response.seckill.goods_objs;
		} 
		// 拼团活动
		if (group_id) {
			response.group = await this.service.marketing.getGroup(group_id);
			// 验证当前商品是否存在活动中
			if (response.group && response.group.goods_id !== goods_id) {
				response.msg = `拼团活动中不存在当前下单商品`;
				return response;
			}
			
			if (group_chief_id) {
				response.group_chief = await this.service.marketing.getGroupChief(group_chief_id);
				// 验证当前拼单否与活动一致
				if (response.group_chief && response.group_chief.group_id !== group_id) {
					response.msg = `拼团活动与拼单团不一致`;
					return response;
				}
				
				// 活动到期时间
				response.group_chief.expires_time = (response.group_chief.expire_time - Date.now()) / 1000;
			}
		} 
		
		let end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.datas = goods;
		response.code = 0;
		response.msg = `获取成功`;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}
	
	
	// 详情
	async detail() {
		let response = {
			code: 1,
			goods: {},
			goods_detail: {},
			goods_skus: [],
			evaluate: [],
			evaluate_cnt: 0,
		};
	
		let start = Date.now();
		const {
			goods_id,
			share_mid
		} = this.ctx.data;
	
		// 产品状态
		let goods_state = '';
		let goods = await this.db.collection('usemall-goods').doc(goods_id).get();
	
		if (!goods || goods.data.length <= 0) {
			response.msg = `当前产品不存在`;
			return response;
		}
		goods_state = goods.data[0].state;
		if (goods_state != '销售中') {
			switch (goods_state) {
				case '待审核':
					response.msg = `当前产品未开售`;
					break;
				case '已下架':
					response.msg = `当前产品已下架`;
					break;
				default:
					response.msg = `当前产品${goods_state}`;
					break;
			}
			return response;
		}
	
		let collected = 0;
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				const collect = await this.db.collection('usemall-member-collect').where({
					create_uid: user.uid,
					goods: goods_id
				}).get();
				// 是否已收藏
				if (collect && collect.data.length > 0 && collect.data[0].state == '已收藏') {
					collected = 1;
				}
	
				// 记录足迹（异步记录，提高响应时间）
				let obj_id = user.uid + goods_id;
				this.db.collection('usemall-goods-history').doc(obj_id).update({
					visit_cnt: this.db.command.inc(1),
					version: this.db.command.inc(1),
					state: goods_state,
					last_modify_uid: user.uid,
					last_modify_time: Date.now()
				}).then(res => {
					if (res && res.updated <= 0) {
						this.db.collection('usemall-goods-history').doc(obj_id).set({
							goods: goods_id,
							sort: 0,
							visit_cnt: 1,
							version: 1,
							state: goods_state,
							create_uid: user.uid,
							create_time: Date.now(),
							last_modify_time: Date.now()
						});
					}
				});
			}
		}
	
		Object.assign(response.goods, { collected }, goods.data[0]);
	
		const detail = this.db.collection('usemall-goods-detail').where({goods_id}).get();
		const sku = this.db.collection('usemall-goods-sku').where({goods_id}).get();
		const evaluate = this.db.collection('usemall-goods-comment').where({goods_id: goods_id,state: '显示'})
			.orderBy('create_time', 'desc')
			.limit(3)
			.get();
		const evaluateCount = this.db.collection('usemall-goods-comment').where({goods_id: goods_id,state: '显示'}).count();
		
		// 获取会员设置项
		const memberParameter = this.db.collection('usemall-member-parameter').limit(1).field({ desc: false, vip_desc: false }).get();
		// 获取积分设置项
		const integralParameter = this.db.collection('usemall-integral-parameter').limit(1).get();
		
		const datas = await Promise.all([detail, sku, evaluate, evaluateCount, memberParameter, integralParameter]);
	
		const detailRes = datas[0];
		const skuRes = datas[1];
		const evaluateRes = datas[2];
		const evaluateCntRes = datas[3];
		const memberParameterRes = datas[4];
		const integralParameterRes = datas[5];
		
		if (detailRes.data && detailRes.data.length === 1) {
			response.goods_detail = detailRes.data[0];
		}
		if (skuRes && skuRes.data) {
			response.goods_skus = skuRes.data;
		}
		if (evaluateCntRes && evaluateCntRes.total) {
			response.evaluate_cnt = evaluateCntRes.total;
			response.evaluate = evaluateRes.data;
		}
		
		response.member_setting = memberParameterRes.data && memberParameterRes.data[0];
		response.integral_setting = integralParameterRes.data && integralParameterRes.data[0];
		
		// 增加测试商品，请勿购买提示 
		// response.goods.name_pw = '【测试商品，请勿购买】' + response.goods.name_pw;
		
		let end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
}
